#!/usr/bin/env sh
set -e

pgver=10 # version to install in Bodhi
pgconf=~/.dots/private/postgresql.conf

if [[ "$OSTYPE" == "darwin"* ]]; then
  brew update && brew install postgresql
  [ -f "$pgconf" ] && ( ln -sfv "$pgconf" /usr/local/var/postgres/postgresql.conf )
  brew services start postgresql
elif [[ "$OSTYPE" == "linux-gnu" ]]; then
  sudo apt update && sudo apt install "postgresql-$pgver" "postgresql-client-$pgver"
  [ -f "$pgconf" ] && ( ln -sfv "$pgconf" "/etc/postgresql/$pgver/main/postgresql.conf" )
  sudo service postgresql start
fi

ln -sfv ~/.dots/postgres/.psqlrc ~/.psqlrc

echo "Creating admin user $USER"
createuser --username=postgres --pwprompt --createdb --createrole $USER
createdb --owner=$USER $USER
psql -c 'Revoke Create On Schema public from Public;'\
     -c "Create Schema communal Authorization postgres;"\
     -c 'Set search_path To communal;'\
     -c 'Drop Schema public;'

pghba=~/.dots/private/pg_hba.conf
if [ -f "$pghba" ] && [[ "$OSTYPE" == "darwin"* ]]; then
  ln -sfv "$pghba" /usr/local/var/postgres/pg_hba.conf
elif [ -f "$pghba" ] && [[ "$OSTYPE" == "linux-gnu" ]]; then
  ln -sfv ~/.dots/private/pg_hba.conf "/etc/postgres/$pgver/main/pg_hba.conf"
fi
